/**
 * 
 */
package pl.net.beercrm.controller;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import pl.net.beercrm.util.PropertiesUtil;

/**
 * @author Rafi
 * 
 */
@Controller
@RequestMapping("/crm.do")
public class ConsoleController {

	private static final Log log = LogFactory.getLog(ConsoleController.class);

	private Properties properties;

	private List<String> propertyKeys = new ArrayList<String>();

	private boolean isRestart = false;

	@RequestMapping("*")
	public String homePage(HttpServletRequest request, ModelMap model,
			HttpSession session) {
		if (properties == null) {
			try {
				prepareData();
			} catch (IOException e) {
				log.error("Fetching properties from classpath failed!", e);
			}
		}
		log.debug("Properties count: " + properties.toString());
		model.addAttribute("properties", properties);
		if (isRestart) {
			session.setAttribute("restart", "true");
		}
		log.debug(request.getRequestURL().toString());
		return "/index.jsp";
	}

	@RequestMapping(params = "action=edit")
	public String edit(HttpServletRequest request, ModelMap model) {
		if (properties != null) {
			model.addAttribute("properties", properties);
			model.addAttribute("propsKeys", propertyKeys);
		}
		log.debug(request.getRequestURL().toString());
		return "/edit.jsp";
	}

	@RequestMapping(params = "action=save")
	public String save(@RequestParam("propsMap") List<String> propsMap,
			HttpServletRequest request, ModelMap model, HttpSession session)
			throws IOException, URISyntaxException {
		log.debug("Properties updated: " + propsMap.size());
		log.debug(request.getRequestURL().toString());
		Properties updatedProperties = new Properties();
		for (String prop : propsMap) {
			String[] split = prop.split("=");
			if (split.length == 2) {
				updatedProperties.put(split[0], split[1]);
			} else {
				throw new IllegalArgumentException(
						"Exception during parsing properties from view layer!",
						new IndexOutOfBoundsException(
								"Expecting two elements in array!"));
			}
		}
		PropertiesUtil.setProperties(updatedProperties);
		PropertiesUtil.storeProperties();
		try {
			prepareData();
		} catch (IOException e) {
			log.error("Fetching properties from classpath failed!", e);
		}
		model.addAttribute("properties", properties);
		this.isRestart = true;
		session.setAttribute("restart", "true");
		return "/index.jsp";
	}

	private void prepareData() throws IOException {
		propertyKeys.clear();
		properties = PropertiesUtil.getProperties();
		for (Object key : properties.keySet()) {
			propertyKeys.add((String) key);
		}
	}

}
